const api = require('../../../utils/api')

Page({
  data: {
    merchantInfo: {},
    overview: {
      orderCount: 0,
      income: '0.00',
      productCount: 0
    }
  },

  onLoad() {
    this.loadMerchantInfo()
    this.loadOverview()
  },

  onShow() {
    this.loadMerchantInfo()
    this.loadOverview()
  },

  async loadMerchantInfo() {
    try {
      const merchantInfo = wx.getStorageSync('merchantInfo')
      const merchantToken = wx.getStorageSync('merchant_token')
      
      if (!merchantInfo || !merchantToken) {
        console.error('未找到商家信息或凭证')
        wx.redirectTo({
          url: '/pages/admin/login/login'
        })
        return
      }
      
      if (merchantInfo) {
        this.setData({ merchantInfo })
      }
    } catch (error) {
      console.error('Failed to load merchant info:', error)
      wx.redirectTo({
        url: '/pages/admin/login/login'
      })
    }
  },

  async loadOverview() {
    try {
      const res = await api.getAdminOverview()
      if (res.success) {
        this.setData({
          overview: res.data
        })
      } else {
        throw new Error(res.message || '加载数据失败')
      }
    } catch (error) {
      console.error('加载概览数据失败:', error)
      wx.showToast({
        title: error.message || '加载数据失败',
        icon: 'none',
        duration: 2000
      })
    }
  },

  navigateTo(e) {
    const url = e.currentTarget.dataset.url
    wx.navigateTo({
      url,
      fail(err) {
        console.error('Navigation failed:', err)
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        })
      }
    })
  },

  handleLogout() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除商家信息
          wx.removeStorageSync('merchant_token')
          wx.removeStorageSync('merchantInfo')
          
          // 跳转到登录页
          wx.reLaunch({
            url: '/pages/admin/login/login'
          })
        }
      }
    })
  }
}) 